/**
 *
 *  @description 拖拽组件
 * */
import { useDrop } from "react-dnd";
import useComponentStore, { Position } from "../store";
import { DragMethod } from "../components/Editor/MaterialArea/ComponentButton";

export const useDropComponent = (
  id: number,
  accept: Array<string>,
  position?: Position
): { isOver: boolean; drop: any } => {
  const { addComponent, updateComponent, moveComponent } = useComponentStore();
  // 拖放
  const [{ isOver }, drop] = useDrop({
    accept,
    collect: (monitor) => ({
      isOver: monitor.isOver({ shallow: true }), // 仅当直接悬停时返回true
    }),
    drop: (item: any, monitor) => {
      // TODO: 处理拖放事件
      // 新增组件
      if (monitor.didDrop()) return; // 在 React DnD 中阻止事件冒泡可以通过 monitor.didDrop() 检测是否已被子组件处理。
      let initComponent = {
        id: new Date().getTime(),
        name: item.type,
        desc: item.desc,
        props: {},
        children: [],
      };
      if (item.method === DragMethod.ADD) {
        // 新增组件
        if (position) {
          updateComponent(initComponent, id, position);
          return;
        }
        addComponent(initComponent, id);
      } else {
        // 移动组件
        if (position) moveComponent(item.id, id, position);
        else moveComponent(item.id, id);
      }
    },
  });

  return { isOver, drop };
};
